<template>
	<view class="u-select-data" :style="{ height: componentHeight }">
		<!-- 输入区域容器 -->
		<view class="select-input-wrap" @click="handleContainerClick" :class="{ 'disabled': disabled }"
			:style="{ minHeight: inputMinHeight }">
			<!-- 文本显示区域 -->
			<view class="select-text">
				<text class="text-content"
					:class="{ 'has-value': selectedValues.length > 0, 'placeholder': !selectedValues.length }">
					{{ displayText || placeholder }}
				</text>

				<!-- 清除按钮 -->
				<u-icon name="close-circle" size="24" class="clear-icon"
					v-if="!disabled && selectedValues.length > 0 && clearable"
					@click="(e) => handleClearAll(e)"></u-icon>
			</view>

			<!-- 下拉箭头 -->
			<u-icon name="arrow-down" size="18" class="arrow-icon"
				:class="{ 'rotate': showPopup, 'disabled': disabled }" @click="(e) => handleArrowClick(e)"></u-icon>
		</view>

		<!-- 弹出层 -->
		<u-popup v-model="showPopup" mode="bottom" @close="onClosePopup" @open="onOpenPopup" ref="selectPopup">

			<!-- 搜索框 -->
			<view class="popup-search">
				<u-input v-model="searchText" placeholder="搜索..." :clearable="true" @input="handleSearch"
					class="search-input"></u-input>
			</view>

			<!-- 列表内容 -->
			<scroll-view scroll-y="true" style="max-height: 600rpx;">
				<view class="popup-content">
					<view class="no-data" v-if="filteredList.length === 0 && !isLoading">
						<text>无匹配数据</text>
					</view>
					<view class="no-data" v-if="isLoading">
						<text>加载中...</text>
					</view>

					<view class="option-item" v-for="(item, index) in filteredList" :key="item[valueKey] + index"
						@click="(e) => toggleSelect(e, item)" :class="{ 'forbidden': isForbidden(item) }">
						<text class="option-text">{{ item[labelKey] }}</text>
						<u-icon name="checkbox-mark" size="18" class="check-icon" v-if="isSelected(item)"></u-icon>
						<u-icon name="lock" size="18" class="forbidden-icon" v-if="isForbidden(item)"></u-icon>
					</view>
				</view>
			</scroll-view>
			<view class="popup-footer" v-if="multiple">
				<u-button type="default" size="mini" @click="clearAll"
					:disabled="selectedValues.length === 0 || disabled || !clearable">
					清空
				</u-button>
				<u-button type="primary" size="mini" @click="confirmSelect" :disabled="disabled">
					确定
				</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: 'u-select-data',
		props: {
			options: {
				type: Array,
				default: () => []
			},
			valueKey: {
				type: String,
				default: 'itemValue'
			},
			labelKey: {
				type: String,
				default: 'itemText'
			},
			forbiddenKey: {
				type: String,
				default: 'forbidden'
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			componentHeight: {
				type: String,
				default: 'auto'
			},
			inputMinHeight: {
				type: String,
				default: '65rpx'
			},
			maxDisplayLength: {
				type: Number,
				default: 18
			},
			value: {
				type: [Array, String, Number, null],
				default: null
			},
			multiple: {
				type: Boolean,
				default: false
			},
			disabled: {
				type: Boolean,
				default: false
			},
			clearable: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				showPopup: false,
				searchText: '',
				filteredList: [],
				selectedValues: [],
				displayText: '',
				isInitialized: false,
				isLoading: false, // 新增：加载状态标记
				// 用于强制更新的key
				updateKey: 0
			};
		},
		mounted() {
			// 初始化时立即处理选项数据
			this.initializeOptions();
			// 处理默认值
			this.handleDefaultValue(this.value);
			this.isInitialized = true;
		},
		watch: {
			value: {
				immediate: false,
				handler(val) {
					if (this.isInitialized) {
						this.handleDefaultValue(val);
						// 触发视图更新
						this.updateKey++;
					}
				}
			},
			options: {
				immediate: true, // 初始就监听options变化
				deep: true,
				handler(newVal) {
					this.initializeOptions(newVal);
					if (this.isInitialized) {
						this.handleDefaultValue(this.value);
					}
				}
			},
			selectedValues: {
				deep: true,
				handler() {
					this.updateDisplayText();
					// 当选中值变化时强制更新视图
					this.$forceUpdate();
				}
			}
		},
		methods: {
			// 新增：专门用于初始化选项的方法
			initializeOptions(newOptions) {
				const optionsToUse = newOptions || this.options;
				// 确保filteredList初始化
				this.filteredList = [...optionsToUse];
			},

			handleDefaultValue(val) {
				// 确保options存在
				if (!this.options || this.options.length === 0) {
					this.selectedValues = [];
					this.updateDisplayText();
					return;
				}

				// 处理多选情况
				if (this.multiple) {
					const arr = Array.isArray(val) ? val : [];
					const newSelected = [];

					arr.forEach(v => {
						const found = this.options.find(item => item[this.valueKey] === v);
						if (found) {
							newSelected.push({
								...found
							});
						}
					});

					this.selectedValues = newSelected;
				} else {
					// 处理单选情况
					if (val !== null && val !== undefined && val !== '') {
						const found = this.options.find(item => item[this.valueKey] === val);
						this.selectedValues = found ? [{
							...found
						}] : [];
					} else {
						this.selectedValues = [];
					}
				}

				this.updateDisplayText();
			},

			isForbidden(item) {
				return item[this.forbiddenKey] === true;
			},

			handleContainerClick() {
				if (!this.disabled) {
					this.openPopup();
				}
			},

			handleArrowClick(e) {
				if (e && typeof e.stopPropagation === 'function') {
					e.stopPropagation();
				} else if (window.event && typeof window.event.cancelBubble !== 'undefined') {
					window.event.cancelBubble = true;
				}

				if (!this.disabled) {
					this.openPopup();
				}
			},

			handleClearAll(e) {
				if (e && typeof e.stopPropagation === 'function') {
					e.stopPropagation();
				} else if (window.event && typeof window.event.cancelBubble !== 'undefined') {
					window.event.cancelBubble = true;
				}

				if (!this.disabled && this.clearable) {
					this.clearAll();
				}
			},

			// 新增：弹窗打开时的处理
			onOpenPopup() {
				// 确保弹窗打开时数据已加载
				this.isLoading = true;
				this.$nextTick(() => {
					this.handleSearch();
					this.isLoading = false;
				});
			},

			openPopup() {
				this.showPopup = true;
			},

			onClosePopup() {
				this.showPopup = false;
				this.searchText = '';
				// 关闭时重置筛选列表
				this.filteredList = [...this.options];
			},

			handleSearch() {
				if (!this.options || this.options.length === 0) {
					this.filteredList = [];
					return;
				}

				if (!this.searchText) {
					this.filteredList = [...this.options];
				} else {
					const searchStr = this.searchText.toLowerCase();
					this.filteredList = this.options.filter(item => {
						return item[this.labelKey] &&
							item[this.labelKey].toLowerCase().includes(searchStr);
					});
				}
			},

			isSelected(item) {
				return this.selectedValues.some(v => v[this.valueKey] === item[this.valueKey]);
			},

			toggleSelect(e, item) {
				if (e && typeof e.stopPropagation === 'function') {
					e.stopPropagation();
				} else if (window.event && typeof window.event.cancelBubble !== 'undefined') {
					window.event.cancelBubble = true;
				}

				if (this.disabled || this.isForbidden(item)) return;

				if (this.multiple) {
					const index = this.selectedValues.findIndex(
						v => v[this.valueKey] === item[this.valueKey]
					);

					// 创建新数组触发更新
					const newSelected = [...this.selectedValues];

					if (index > -1) {
						newSelected.splice(index, 1);
					} else {
						newSelected.push({
							...item
						});
					}

					this.selectedValues = newSelected;
					this.emitChange();
				} else {
					this.selectedValues = [{
						...item
					}];
					this.showPopup = false;
					this.emitChange();
				}
			},

			clearAll() {
				if (this.disabled || !this.clearable) return;

				// 直接替换数组引用
				this.selectedValues = [];
				this.displayText = '';
				this.emitChange();

				// 强制更新视图
				this.$forceUpdate();
			},

			confirmSelect() {
				if (this.disabled) return;

				this.showPopup = false;
				this.emitChange();
			},

			updateDisplayText() {
				if (this.selectedValues.length === 0) {
					this.displayText = '';
					return;
				}

				const labels = this.selectedValues.map(item => item[this.labelKey] || '');
				let text = labels.join('，');

				if (text.length > this.maxDisplayLength) {
					text = text.substring(0, this.maxDisplayLength) + '...';
				}

				this.displayText = text;
			},

			emitChange() {
				let values;
				if (this.multiple) {
					values = this.selectedValues.map(item => item[this.valueKey]);
				} else {
					values = this.selectedValues.length > 0 ? this.selectedValues[0][this.valueKey] : null;
				}
				this.$emit('input', values);
				this.$emit('change', values);

				// 确保视图更新
				this.$forceUpdate();
			}
		}
	};
</script>

<style scoped lang="scss">
	.u-select-data {
		position: relative;
		width: 100%;
	}

	.select-input-wrap {
		display: flex;
		align-items: center;
		padding: 0 16rpx;
		border: 1px solid #e5e5e5;
		border-radius: 8rpx;
		min-height: 80rpx;
		cursor: pointer;
		transition: all 0.2s;
	}

	.select-input-wrap.disabled {
		border-color: #e5e5e5;
		background-color: #f5f5f5;
		cursor: not-allowed;
	}

	.select-text {
		flex: 1;
		min-width: 120rpx;
		font-size: 28rpx;
		padding: 0 8rpx;
		position: relative;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.text-content {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		flex: 1;
	}

	.text-content.placeholder {
		color: #999;
	}

	.text-content.has-value {
		color: #333;
	}

	.clear-icon {
		color: #999;
		margin-left: 8rpx;
		cursor: pointer;
		position: absolute;
		right: 0;

		&:active {
			color: #666;
		}
	}

	.arrow-icon {
		color: #666;
		margin-left: 8rpx;
		transition: transform 0.3s ease;
		cursor: pointer;
	}

	.arrow-icon.disabled {
		color: #ccc;
	}

	.rotate {
		transform: rotate(180deg);
	}

	.popup-search {
		padding: 16rpx;
		border-bottom: 1px solid #eee;
	}

	.search-input {
		font-size: 28rpx;
	}

	.popup-content {
		// max-height: 600rpx;
		// overflow-y: auto;
	}

	.option-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		border-bottom: 1px solid #eee;
		font-size: 28rpx;
		transition: background-color 0.2s;

		&:active {
			background-color: #f5f5f5;
		}
	}

	.option-item.forbidden {
		color: #999;
		cursor: not-allowed;

		&:active {
			background-color: transparent;
		}
	}

	.check-icon {
		color: #1677ff;
	}

	.forbidden-icon {
		color: #999;
	}

	.no-data {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200rpx;
		color: #999;
		font-size: 28rpx;
	}

	.popup-footer {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
		padding: 16rpx;
		border-top: 1px solid #eee;
	}
</style>